package com.voice.call.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import voice.voice.call.cache.ConfigSystemCache;

import com.voice.call.common.Const;
import com.voice.call.common.Result;
import com.voice.call.entity.ConsumeLog;
import com.voice.call.entity.SupportMcc;
import com.voice.call.entity.UserAccount;
import com.voice.call.mapper.ConsumeLogMapper;
import com.voice.call.service.ConsumeLogService;
import com.voice.call.service.SupportMccService;
import com.voice.call.service.UserAccountService;
import com.voice.call.utils.DateUtil;
import com.voice.call.utils.StringUtil;

@Service
public class ConsumeLogServiceImpl implements ConsumeLogService{
	
	private static final Logger log = LoggerFactory.getLogger(ConsumeLogServiceImpl.class);
	
	@Resource
	private ConsumeLogMapper consumeLogMapper;
	
	@Resource
	private ConfigSystemCache configSystemCache;
	
	@Resource
	private SupportMccService supportMccService;
	
	@Resource
	private UserAccountService userAccountService;
	
	//新增消费记录
	@Override
	public boolean addConsumeLog(Integer user_id,String name,String type,Integer money,boolean addIncome,String remark){
		
		try {
			
			ConsumeLog entity = new ConsumeLog();
			entity.setUserId(user_id);
			entity.setName(name);
			entity.setType(type);
			entity.setMoney(money);
			entity.setIsIncome(addIncome?Const.Y:Const.N);
			if(!StringUtil.isEmpty(remark)){
				entity.setRemark(remark);
			}
			entity.setCtime(new Date());
			
			if (consumeLogMapper.insert(entity)>0) {
				log.info("新增消费记录成功");
				return true;
			}
			log.error("新增消费记录成功");
			return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("新增消费记录发生异常");
			return false;
		}
		
		
	}
	
	@Override
	public Result getConsumeLogForUserIdList(Integer user_id,String lang){
		
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("lang", lang);
		List<ConsumeLog> list = consumeLogMapper.list(paramsMap);
		List<Map<String, Object>> rsList = new ArrayList<Map<String,Object>>();
		if(list!=null && !list.isEmpty()){
			
			for (ConsumeLog item:list) {
				Map<String, Object> rsMap = new HashMap<String, Object>();
				rsMap.put("name", item.getName());
				rsMap.put("money", item.getMoney());
				rsMap.put("isIncome", item.getIsIncome());
				String timeStr = DateUtil.getTimeStringByDate(item.getCtime(), "yyyy/MM/dd");
				rsMap.put("ctime", timeStr.substring(2));
				rsList.add(rsMap);
			}
			
		}
		return new Result(rsList);
	}
	
	/***
	 * 新增某个分类积分
	 * @param category 类别
	 * @param ip       ip地址
	 * @param name     说明
	 * @param addIncome  true:收入，false:支出
	 * @param remark     备注
	 * @return
	 */
	@Override
	public boolean addCategoryConsumeLog(String category,String ip,Integer user_id,String name,boolean addIncome,String remark,StringBuilder sbIntegral){
		
		try {
			
			SupportMcc supportMcc = supportMccService.getSupportCategoryIntegral(category, ip);
			if (supportMcc == null) {
				log.info("未配置当前类别积分,category={}",category);
				return true;
			}
			if (supportMcc.getIntegral().equals(0)) {
				log.info("当前类别积分配置为0,category={}",category);
				return true;
			}
			
			UserAccount ua = userAccountService.getUserAccountForUserId(user_id);
			if (ua == null) {
				log.error("获取积分帐户失败");
				return false;
			}
			//更新积分帐户
			if(userAccountService.updateAccountBlance(user_id, supportMcc.getIntegral(), addIncome)){
				log.info("添加帐户积分成功");
				//添加积分记录
				if (this.addConsumeLog(user_id, name, category, supportMcc.getIntegral(), addIncome, remark)) {
					
					if (sbIntegral!=null) {
						sbIntegral.append(supportMcc.getIntegral());
					}
					log.info("添加积分记录成功");
					return true;
				}else {
					log.error("添加积分记录失败");
				}
			}else {
				log.error("添加帐户积分失败");
			}
			return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加积分记录失败");
			return false;
		}
		
		
		
		
	}
	
	//判断是否超过当日积分最大限制
	@Override
	public	boolean hasOverMaxIntegralLimit(Integer user_id){
		String maxLimit = configSystemCache.get(Const.SYSTEM_INTEGRAL_LIMIT);
		if (StringUtil.isEmpty(maxLimit)) {
			log.info("未配置最大积分限制");
			return false;
		}
		
		String nowString=DateUtil.getNowDateTimeString(DateUtil.DATE_FMT);
		
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("isIncome", Const.Y);
		paramsMap.put("types", new String[]{Const.TASK_INVITE,Const.TASK_INVITE_EXTRA});
		paramsMap.put("startTime", nowString+" 00:00:00");
		paramsMap.put("endTime", nowString+" 23:59:59");
		
		Integer total = consumeLogMapper.getTodayMaxIntegral(paramsMap);
		
		if (total!=null&&total.intValue() >= Integer.valueOf(maxLimit).intValue()) {
			return true;
		}
		return false;
		
	}
	
	//获取今天积分
	@Override
	public	int getTodayIntegral(Integer user_id){
        String nowString=DateUtil.getNowDateTimeString(DateUtil.DATE_FMT);
		
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("isIncome", Const.Y);
		paramsMap.put("types", new String[]{Const.TASK_LEVEL}); //排除用户等级积分
		paramsMap.put("startTime", nowString+" 00:00:00");
		paramsMap.put("endTime", nowString+" 23:59:59");
		
		Integer total = consumeLogMapper.getTodayMaxIntegral(paramsMap);
		if (total==null) {
			return 0;
		}
		return total.intValue();
	}
	
	//获取老虎机当天已玩次数
	@Override
	public	int getLuckyCreditPlayTotal(Integer user_id){
		
		String nowString=DateUtil.getNowDateTimeString(DateUtil.DATE_FMT);
		
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("type", Const.TASK_LUCKY_CREDIT);
		paramsMap.put("startTime", nowString+" 00:00:00");
		paramsMap.put("endTime", nowString+" 23:59:59");
		
		return consumeLogMapper.getLuckyCreditCount(paramsMap);
	}
	
	//判断是否已绑定手机 
	@Override
	public	boolean existsBindPhone(Integer user_id){
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("type", Const.TASK_BIND_PHONE);
		int total = consumeLogMapper.getBindPhoneCount(paramsMap);
		return total>0?true:false;
	}
	
	@Override
	public boolean existsLevelLogsForUserId(Integer user_id,Integer level){
		String nowString=DateUtil.getNowDateTimeString(DateUtil.DATE_FMT);
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("type", Const.TASK_LEVEL);
		paramsMap.put("level", String.valueOf(level));
		paramsMap.put("startTime", nowString+" 00:00:00");
		paramsMap.put("endTime", nowString+" 23:59:59");
		int total = consumeLogMapper.getTodayLevelLogCount(paramsMap);
		if (total > 0) {
			return true;
		}
		return false;
	}
	
	//判断视频积分是否超过当日视频积分最大限制
	@Override
	public	boolean hasOverMaxVideoIntegralLimit(Integer user_id){
		
		String maxLimit = configSystemCache.get(Const.SYSTEM_VIDEO_INTEGRAL_LIMIT);
		if (StringUtil.isEmpty(maxLimit)) {
			log.info("未配置视频最大积分限制");
			return false;
		}
		
		String nowString=DateUtil.getNowDateTimeString(DateUtil.DATE_FMT);
		
		Map<String, Object> paramsMap =new HashMap<String, Object>();
		paramsMap.put("userId", user_id);
		paramsMap.put("isIncome", Const.Y);
		paramsMap.put("type", Const.TASK_VIDEO);
		paramsMap.put("startTime", nowString+" 00:00:00");
		paramsMap.put("endTime", nowString+" 23:59:59");
		
		Integer total = consumeLogMapper.getTypeTodayMaxIntegral(paramsMap);
		if (total!=null && total.intValue() >= Integer.valueOf(maxLimit).intValue()) {
			return true;
		}
		return false;
	}

}
